import router from './router'
import store from '@/store'

// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { asyncRoutes } from '@/router'
const whiteList = ['/login', '/404'] // no redirect whitelist
// 导航守卫只能根据访问的path和token（有无）来控制用户的访问权限
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    // 这里的token万一是伪造的token??
    if (to.path === '/login') {
      next('/')
      console.log('被拦截了吗？、')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.username) {
        const resObj = await store.dispatch('user/actionsGetUserInfo')
        // console.log(resObj.roles.menus)
        // console.log(asyncRoutes)

        const otherRoutes = asyncRoutes.filter(item => resObj.roles.menus.includes(item.children[0].name))
        store.commit('permission/setRoute', otherRoutes)
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        next({
          ...to,
          replace: true
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach((to, form) => {
  NProgress.done()
})
